/**
 * Created by xuelei.kong on 2017/7/16.
 */
var forEach = function (arr, fn) {
    var len = arr.length;
    for (var i = 0; i < len; i++) {
        var tmp = arr[i];
        if (fn.call(tmp, i, tmp) == false) {
            break;
        }
    }

};

var showDatePicker = function (obj, type) {
    if (type === 1) {
        WdatePicker({
            maxDate: $(obj).parents('.filter-wrapper').find(".to").val(),
            onpicked: function () {
                $(obj).blur();
            }
        })
    } else {
        WdatePicker({
            minDate: $(obj).parents('.filter-wrapper').find(".from").val(),
            onpicked: function () {
                $(obj).blur();
            }
        })
    }

};
function formatDate(date, fmt) {
    var D = new Date(date);
    var o = {
        "M+": D.getMonth() + 1, //月份
        "d+": D.getDate(), //日
        "h+": D.getHours(), //小时
        "m+": D.getMinutes(), //分
        "s+": D.getSeconds(), //秒
        "q+": Math.floor((D.getMonth() + 3) / 3), //季度
        "S": D.getMilliseconds() //毫秒
    };

    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (D.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
var app = new Vue({
    el: '#app',
    data: function () {
        return {
            loadingFlag: false,
            ztreeLoadingFlag: false,
            startDate: formatDate(new Date().getTime()-24*60*60*1000,'yyyy-MM-dd'),
            endDate: formatDate(new Date().getTime(),'yyyy-MM-dd'),
            equipmentID: [],
            equipment: [],
            ascOption: {
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    },
                    backgroundColor: '#001c22',
                    formatter: function (params) {
                        return '<div style="padding: 0 5px;">' +
                            '<p style="font-size:14px;color:#00ece0;">用能排名</p>' +
                            '<p style="font-size: 12px;color:#00ece0;"><span style="color:#006772">用能名次：</span><i style="color:#07f900">' + params[0].axisValueLabel +'</i></p>' +
                            '<p style="font-size: 12px;color:#00ece0;"><span style="color:#006772">设备名称：</span>' + params[0].data.name + '</p>' +
                            '<p style="font-size: 12px;color:#00ece0;"><span style="color:#006772">设备用量：</span>' + params[0].data.value + '</p>' +
                            '</div>'
                    }

                },
                grid: {
                    left: '3%',
                    right: '10%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        name: "名次",
                        axisLine: {
                            lineStyle: {
                                color: '#008078'
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#00f3ff'
                            }
                        },

                        type: 'category',
                        data: [],
                        axisTick: {
                            alignWithLabel: true
                        }
                    }
                ],
                yAxis: [
                    {
                        name: "用电量（KWH）",
                        splitLine: {
                            lineStyle: {
                                type: "doote",
                                color: '#4a6b70'

                            }
                        },
                        type: 'value',
                        axisLine: {
                            lineStyle: {
                                color: '#008078'
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#00f3ff'
                            }
                        }
                    }
                ],
                series: [
                    {
                        name: '',
                        type: 'bar',
                        barWidth: 20,

                        data: [],
                        itemStyle: {
                            normal: {
                                //好，这里就是重头戏了，定义一个list，然后根据所以取得不同的值，这样就实现了，
                                color: function (params) {
                                    // build a color map as your need.
                                    var colorList = [
                                        '#e76d1a', '#cf7c17', '#b98c13', '#a39c0e', '#8daa0c',
                                        '#7aba07', '#68c904', '#5bd802', '#53e902', '#07f900',
                                        '#D7504B', '#C6E579', '#F4E001', '#F0805A', '#26C0C0'
                                    ];
                                    return colorList[params.dataIndex]
                                }

                            }
                        }

                    }
                ]
            },
            descOption: {
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    },
                    backgroundColor: '#001c22',
                    formatter: function (params) {
                        return '<div style="padding: 0 5px;">' +
                            '<p style="font-size:14px;color:#00ece0;">用能排名</p>' +
                            '<p style="font-size: 12px;color:#00ece0;"><span style="color:#006772">用能名次：</span><i style="color:#07f900">' + params[0].axisValueLabel+ '</i></p>' +
                            '<p style="font-size: 12px;color:#00ece0;"><span style="color:#006772">设备名称：</span>' + params[0].data.name + '</p>' +
                            '<p style="font-size: 12px;color:#00ece0;"><span style="color:#006772">设备用量：</span>' + params[0].data.value + '</p>' +
                            '</div>'
                    }

                },
                grid: {
                    left: '3%',
                    right: '10%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        name: "名次",
                        axisLine: {
                            lineStyle: {
                                color: '#008078'
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#00f3ff'
                            }
                        },

                        type: 'category',
                        data: [],
                        axisTick: {
                            alignWithLabel: true
                        }
                    }
                ],
                yAxis: [
                    {
                        name: "用电量（KWH）",
                        splitLine: {
                            lineStyle: {
                                type: "doote",
                                color: '#4a6b70'

                            }
                        },
                        type: 'value',
                        axisLine: {
                            lineStyle: {
                                color: '#008078'
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: '#00f3ff'
                            }
                        }
                    }
                ],
                series: [
                    {
                        name: '',
                        type: 'bar',
                        barWidth: 20,

                        data: [],
                        itemStyle: {
                            normal: {
                                //好，这里就是重头戏了，定义一个list，然后根据所以取得不同的值，这样就实现了，
                                color: function (params) {
                                    // build a color map as your need.
                                    var colorList = [
                                        // '#e76d1a', '#cf7c17', '#b98c13', '#a39c0e', '#8daa0c',
                                        // '#7aba07', '#68c904', '#5bd802', '#53e902', '#07f900',


                                        '#07f900', '#53e902', '#5bd802', '#68c904', '#7aba07',
                                        '#8daa0c', '#a39c0e', '#b98c13', '#cf7c17', '#e76d1a'
                                    ];
                                    return colorList[params.dataIndex]
                                }

                            }
                        }

                    }
                ]
            },
            pieOption: {
                // backgroundColor: '#001c22',

                title: {
                    text: '',
                    left: 'center',
                    top: 20,
                    textStyle: {
                        color: '#ccc'
                    }
                },

                tooltip: {
                    trigger: 'item',
                    color: '#01fdf0',
                    backgroundColor: '#001c22',
                    // formatter: "{b} : {c} ({d}%)"
                    formatter: function (params) {
                        console.log(params);
                        return '<p style="font-size: 14px;color:#01fdf0">' + params.name + '</p>' +
                            '<p style="font-size:12px;color:#01fdf0">' + params.value + '    (' + params.percent + '%)</p>'
                    }
                },

                visualMap: {
                    show: false,
                    min: 80,
                    max: 6000000,
                    inRange: {
                        // colorLightness: [0, 0]
                    }
                },
                series: [
                    {
                        name: '',
                        type: 'pie',
                        radius: '55%',
                        center: ['50%', '50%'],
                        data: [].sort(function (a, b) {
                            return a.value - b.value;
                        }),
                        roseType: 'radius',
                        label: {
                            normal: {
                                textStyle: {
                                    color: '#01fdf0'
                                }
                            }
                        },
                        labelLine: {
                            normal: {
                                lineStyle: {
                                    color: '#84bfa5'
                                },
                                smooth: 0.2,
                                length: 10,
                                length2: 20
                            }
                        },
                        itemStyle: {
                            normal: {
                                color: '#c23531',
                                shadowBlur: 200,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },

                        animationType: 'scale',
                        animationEasing: 'elasticOut',
                        animationDelay: function (idx) {
                            return Math.random() * 200;
                        }
                    }
                ]
            }


        }
    },
    mounted: function () {

        //ztree

        var that = this;
        // this.loadingFlag = true;
        $.ajax({
            url: "http://180.166.106.206:8086/Data/GetTree",
            type: 'GET',
            success: function (res) {
                console.log(res);
                var code;

                function setCheck() {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                        py = $("#py").attr("checked") ? "p" : "",
                        sy = $("#sy").attr("checked") ? "s" : "",
                        pn = $("#pn").attr("checked") ? "p" : "",
                        sn = $("#sn").attr("checked") ? "s" : "",
                        // type = {"Y": py + sy, "N": pn + sn};
                        type = {"Y": "", "N": ""};

                    zTree.setting.check.chkboxType = type;
                    showCode('setting.check.chkboxType = { "Y" : "' + type.Y + '", "N" : "' + type.N + '" };');
                }

                function showCode(str) {
                    if (!code) code = $("#code");
                    code.empty();
                    code.append("<li>" + str + "</li>");
                }

                var setting = {
                    check: {
                        enable: true
                    },

                    data: {
                        simpleData: {
                            enable: true
                        }
                    },

                    view: {
                        fontCss: setHighlight // 高亮一定要设置，setHighlight是自定义方法
                    },

                    callback: {
                        onCheck: onCheck


                    }
                };
                that.ztree = $.fn.zTree.init($("#treeDemo"), setting, res.zNodes);
                that.ztreeLoadingFlag = false;
                var node = that.ztree.getNodeByParam("id", res.zNodes[0].id);
                that.ztree.checkNode(node);
                that.equipmentID.push(res.zNodes[0].id);
                that.equipment.push(res.zNodes[0].name);
                that.ztree.cancelSelectedNode();
                //禁用所有叶子节点
                var allNode = that.ztree.transformToArray(that.ztree.getNodes());

                for (var i = 0; i < allNode.length; i++) {
                    if (!allNode[i].isParent) {
                        that.ztree.setChkDisabled(allNode[i], true);
                    }
                }


                /*var jbfxMyChart = echarts.init(document.getElementById('jbfx'));
                jbfxMyChart.setOption(that.lineOption);*/
                that.getData();

                // 设置高亮字体
                function setHighlight(treeId, treeNode) {
                    console.log(treeNode);
                    return (treeNode.highlight) ? {
                        color: "#EB6100"
                        // "font-weight": "bold",
                        // "background-color": "#EB6100"
                    } : {color: "#01fcf0", "font-weight": "normal"};
                }


                // var node = zTree.getNodeByParam("id",5001);
                // zTree.selectNode(node);

                setCheck();
                $("#py").bind("change", setCheck);
                $("#sy").bind("change", setCheck);
                $("#pn").bind("change", setCheck);
                $("#sn").bind("change", setCheck);

                function onCheck(e, treeId, treeNode) {
                    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                    var nodes = treeObj.getCheckedNodes(true);
                    console.log(nodes);
                    var v = "";
                    that.equipment = [];
                    that.equipmentID = [];
                    for (var i = 0; i < nodes.length; i++) {
                        v += nodes[i].name + ",";
                        if (!nodes[i].children) {

                        }
                        if (nodes[i].id !== treeNode.id) {
                            treeObj.checkNode(nodes[i], false);
                        } else {
                            that.equipmentID.push(nodes[i].id);
                            that.equipment.push(nodes[i].name);
                        }


                    }



                }

                // that.drawChart();

            }

        });


    },
    methods: {
        search: function () {

            if (!this.startDate || !this.endDate) {
                alert("请选择起止时间")
            } else if (!this.equipmentID.length) {
                alert('请选择设备');
            } else {
                this.getData();
            }
        },
        getData: function () {
            var that = this;
            that.loadingFlag = true;
            $.ajax({
                url: "http://180.166.106.206:8086/DataQuery/GetOrderData?id=" + that.equipmentID[0] + "&begin=" + that.startDate + "&end=" + that.endDate,
                dataType: 'json',
                type: "POST",
                success: function (res) {
                    console.log(res);
                    that.loadingFlag = false;
                    var ascData = res.List[0].OrderItems.slice(0, 10);
                    var descData = res.List[0].OrderItems.slice(-10).reverse();
                    // {value: 1000, name: 'A'},
                    that.ascOption.series[0].data = [];
                    that.ascOption.xAxis[0].data = [];
                    that.descOption.series[0].data = [];
                    that.descOption.xAxis[0].data = [];
                    that.pieOption.series[0].data = [];
                    forEach(ascData, function (i, item) {
                        that.ascOption.series[0].data.push({
                            name: item.Name,
                            value: item.Val
                        });

                         that.pieOption.series[0].data.push(
                             {
                                 name: item.Name,
                                 value: item.Val
                             }
                         );




                        that.ascOption.xAxis[0].data.push(i+1);
                    });
                    forEach(descData, function (i, item) {
                        that.descOption.series[0].data.push({
                            name: item.Name,
                            value: item.Val
                        });
                        that.descOption.xAxis[0].data.push(i+1);
                    });
                    var ascMyChart = echarts.init(document.getElementById('asc'));
                    ascMyChart.setOption(that.ascOption);


                    var descMyChart = echarts.init(document.getElementById('desc'));
                    descMyChart.setOption(that.descOption);

                    //饼图

                    var pieMyChart = echarts.init(document.getElementById('pie'));
                    pieMyChart.setOption(that.pieOption);
                }
            });
        },

        searchNode: function () {
            var value = this.$refs.ztreesearch.value;
            if (value == "") return;

            // 获取搜索的节点
            var nodes = this.ztree.getNodesByParamFuzzy("name", value);
            // 关闭所有节点的高亮
            var allNodes = this.ztree.transformToArray(this.ztree.getNodes());
            for (var i = 0; i < allNodes.length; i++) {
                allNodes[i].highlight = false;
                this.ztree.updateNode(allNodes[i]);
            }
            // 展开第一层节点
            this.ztree.expandAll(false);
            this.ztree.expandNode(this.ztree.getNodes()[0], true);
            // 高亮并展开搜索到的节点
            for (var i = 0; i < nodes.length; i++) {
                nodes[i].highlight = true;
                this.ztree.updateNode(nodes[i]); // 更新节点，让高亮生效
                this.ztree.expandNode(nodes[i].getParentNode(), true);
            }
        },
        searchNodeLazy: function () {
            var timeoutId = null;
            var that = this;
            var value = event.target.value;
            if (timeoutId) {
                console.log(222);
                clearTimeout(timeoutId);
            }
            timeoutId = setTimeout(function () {
                console.log(111);
                that.searchNode(value);
            }, 500);
        },
        setViewModel: function (which) {
            this[which] = event.target.value;
        }

    }
});


